﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NetNote.Models;

namespace NetNote.Repository
{
    public class NoteRepository : INoteRepository
    {
        private NoteContext _context;

        public NoteRepository(NoteContext context)
        {
            _context = context;
        }
        public Task<Note> GetByidAsync(int id)
        {
            return _context.Notes.Include(type=>type.Type).FirstOrDefaultAsync(s => s.Id == id);
        }

        public Task<List<Note>> ListAsync()
        {
            return _context.Notes.Include(type => type.Type).ToListAsync();
        }

        public Task AddAsync(Note note)
        {
            _context.AddAsync(note);
            return _context.SaveChangesAsync();
        }

        public Task UpdateAsync(Note note)
        {
            _context.Entry(note).State = EntityState.Modified;
            return _context.SaveChangesAsync();
        }

        public Tuple<List<Note>, int> PageList(int pageIndex, int pageSize)
        {
            var query = _context.Notes.Include(type => type.Type).AsQueryable();
            var count = query.Count();

            var pagecount = count%pageSize == 0 ? count/pageSize : count/pageSize + 1;
            var notes =  query.OrderByDescending(s => s.Create).Skip((pageIndex - 1)*pageSize).Take(pageSize).ToList();
            return new Tuple<List<Note>, int>(notes, pagecount);
        }
    }
}
